package com.keur.money.ui.main.fm

import android.Manifest
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.adapter.MullaOnItemChildClickListener
import com.keur.money.base.utils.permission.OnPermissionCallback
import com.keur.money.base.utils.permission.XXPermissions
import com.keur.money.databinding.FmMullaHomeBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpFm
import com.keur.money.ui.main.adapter.KeurProductAdapter
import com.keur.money.ui.main.impl.KeurHomePresenterImpl
import com.keur.money.ui.main.view.IKeurHomeView
import com.keur.money.ui.market.act.KeurApplyAct
import com.keur.money.ui.market.act.KeurOrderDetailsAct
import com.keur.money.ui.steps.act.KeurStepsAct
import com.keur.money.ui.user.act.KeurUserLuckyDrawAct
import com.keur.money.ui.user.act.KeurUserMessageAct
import com.keur.money.utils.dialog.PermissionListDialog
import com.keur.money.utils.event.KeurBehaviorTracker
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import com.keur.money.utils.helper.TestDataLibInvoke
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：首页
 */
class KeurHomeFm : MvpFm<IKeurHomeView, KeurHomePresenterImpl>(),IKeurHomeView {
//    lateinit var binding: FmMullaHomeBinding
    private var _binding: FmMullaHomeBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var pAdapter: KeurProductAdapter? = null

    override fun createPresenter(): KeurHomePresenterImpl {
        return KeurHomePresenterImpl(context)
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaHomeBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaBackBtnRes(R.mipmap.mulla_kefu_dialog_icon)
        setMullaRightBtnRes(R.mipmap.mulla_message_icon)
        setMullaTextTitle(getString(R.string.home_title))
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))
        isInterceptBack(true)
        initMullaRefreshLayout()
        initMullaRecyclerView()

        val showTipsKey = getString(R.string.home_credit_score_result)
        val showTipsText = String.format(getString(R.string.home_credit_score_tips),showTipsKey)
        val spString = SpannableString(showTipsText)
        val start = showTipsText.indexOf(showTipsKey)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFAC25")), start, showTipsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textScoreTips?.text = spString
    }

    override fun initMullaListener() {
        rootViewBinding.ivBaseBack.setOnClickListener {
            showMullaKefuDialog("Home Page")
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"Home Page")
        }
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(KeurUserMessageAct::class.java)
        }
        //抽奖
        _binding?.luckydrawLayout?.btnGo?.setOnClickListener {
            onIntent(KeurUserLuckyDrawAct::class.java)
        }
        //产品列表
        _binding?.productLayout?.setOnClickListener {
            if (presenter.isApply()) {
                return@setOnClickListener
            }
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.GONE

            showMullaLoading(isTOuchOut = false, isCancel = false)
            presenter.checkMullaProductStatus(true)
        }
        //已申请列表
        _binding?.appliedLayout?.setOnClickListener {
            if (!presenter.isApply()) {
                return@setOnClickListener
            }
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.GONE

            showMullaLoading(isTOuchOut = false, isCancel = false)
            presenter.checkMullaProductStatus(false)
        }
        // Apply Now 、 Repay Now
        _binding?.textEmpty?.setOnClickListener {
            if (presenter.isApply()){//apply now
                MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_SHOW_REPAY))
            } else {
                _binding?.productLayout?.callOnClick()
            }
        }
    }

    override fun initMullaData() {
        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }

        presenter.checkMullaProductStatus(true)
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_PRODUCT_LIST_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //刷新流程
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PROCESS_REFRESH))
            //刷新产品列表
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PRODUCT_REFRESH))
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化产品列表
     */
    private fun initMullaRecyclerView() {
        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        pAdapter = KeurProductAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = pAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        pAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = pAdapter?.getItem(position)
            item?.let {
                HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_HOME_PRODUCT, it.optString("product"))
                // TODO: apply 批量埋点上报
                KeurBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)

                presenter.onMullaSetSelectProductInfo(it)
                when (childView.id) {
                    R.id.itemLayout -> {//点击Item
                        //只有 Applied列表才可点击查看详情
                        if (!it.optBoolean("isApply", false)) {
                            val pLogo = it.optString("logo")
                            val pName = it.optString("product")
                            val pToken = it.optString("token")
                            val pTitle = it.optString("name")
                            KeurOrderDetailsAct.start(requireContext(), pLogo, pName, pToken,pTitle)
                        }
                    }

                    R.id.btnApply -> {//申请
                        if ("APPLY" == it.optString("status") && it.optString("activeFlag") == "YES") {
                            if (it.optString("applyStatus").endsWith("DENIED")){//被拒绝 - 进入贷款详情
                                val pLogo = it.optString("logo")
                                val pName = it.optString("product")
                                val pToken = it.optString("token")
                                val pTitle = it.optString("name")
                                KeurOrderDetailsAct.start(requireContext(), pLogo, pName, pToken,pTitle)
                                return@MullaOnItemChildClickListener
                            }
                            presenter.checkMullaAllPermissionsAgree()
                        }
                    }
                }
            }
        })
    }

    /**
     * 产品列表
     */
    override fun showMullaProductsView() {
        checkMullaNormalView()
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))

        _binding?.textProducts?.setTextColor(Color.parseColor("#FF8027FF"))
        _binding?.textProducts?.textSize = 20f
        _binding?.imgProducts?.visibility = View.VISIBLE

        //新用户
        if (isNewUser()){
            _binding?.scoreTipsLayout?.visibility = View.GONE
        } else {
            _binding?.scoreTipsLayout?.visibility = View.VISIBLE
        }
        _binding?.giftLayout?.visibility = View.VISIBLE
    }

    /**
     * 订单列表
     */
    override fun showMullaAppliedViews() {
        checkMullaNormalView()
        setMullaTitleBarColor(Color.parseColor("#FFF1F3F5"))
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFF1F3F5"))

        _binding?.textApplied?.setTextColor(Color.parseColor("#FF8027FF"))
        _binding?.textApplied?.textSize = 20f
        _binding?.imgApplied?.visibility = View.VISIBLE

        _binding?.scoreTipsLayout?.visibility = View.GONE
        _binding?.giftLayout?.visibility = View.GONE
    }

    /**
     * 设置可申请产品列表
     */
    override fun showMullaProductsList(isApply: Boolean,pList: ArrayList<JSONObject>) {
        hideMullaLoading()
        if (pList.size == 0){
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.VISIBLE

            var showText = ""
            var startIndex = 0
            when(isApply){
                true -> {
                    showText = String.format(getString(R.string.home_product_apply_empty),getString(R.string.home_product_apply_repay))
                    startIndex = showText.indexOf(getString(R.string.home_product_apply_repay))
                }
                else -> {
                    showText = String.format(getString(R.string.home_product_applied_empty),getString(R.string.home_product_applied_apply))
                    startIndex = showText.indexOf(getString(R.string.home_product_applied_apply))
                }
            }
            val spString = SpannableString(showText)
            spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF8027FF")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            spString.setSpan(UnderlineSpan(), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textEmpty?.text = spString
            return
        }
        _binding?.recyclerView?.visibility = View.VISIBLE
        _binding?.emptyLayout?.visibility = View.GONE
        pAdapter?.data = pList
    }

    /**
     * 设置未选择状态
     */
    private fun checkMullaNormalView() {
        _binding?.textProducts?.setTextColor(Color.parseColor("#FFE0DBEE"))
        _binding?.textProducts?.textSize = 14f
        _binding?.imgProducts?.visibility = View.INVISIBLE

        _binding?.textApplied?.setTextColor(Color.parseColor("#FFE0DBEE"))
        _binding?.textApplied?.textSize = 14f
        _binding?.imgApplied?.visibility = View.INVISIBLE
    }

    /**
     * 进入权限列表预览页面
     */
    override fun showMullaFlowPermissionList() {
        val perListDialog = PermissionListDialog(context,object : PermissionListDialog.IDialogCallback{
            override fun onMullaKefuClick() {
                showMullaKefuDialog("Permission Page")
                HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"Permission Page")
            }

            override fun onMullaDenyClick() {
                //是否是广告渠道
                val isAdSource = SharedHelper.getKeurSPBoolean(SharedHelper.KEUR_SPKEY.KEUR_IS_ADSOURCE)
                //非广告渠道才继续校验进行下一步
                if (!isAdSource){
                    presenter.checkMullaAllPermissionsAgree()
                }
            }

            override fun onMullaAgreeClick() {
                presenter.checkMullaAllPermissionsAgree()
            }
        })
        perListDialog.setCancelable(false)
        perListDialog.setCanceledOnTouchOutside(false)
        perListDialog.show()
    }

    /**
     * 权限验证成功
     */
    override fun showMullaCheckPermissionSuccess() {
        //权限列表操作状态 0未操作  1已同意  -1拒绝
        val perListStatus = SharedHelper.getKeurSPInt(SharedHelper.KEUR_SPKEY.KEUR_PERMISSION_LIST_STATUS)
        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (perListStatus == 1 && XXPermissions.isGranted(requireContext(), Manifest.permission.READ_SMS)){
            //上报设备数据
            TestDataLibInvoke.takeKeurMoneyDeviceInfoTypsAction()
        }
        presenter.checkMullaAllStepsAction()
    }

    /**
     * 认证已完成 - 进入申贷页面
     */
    override fun showMullaApplyPage(pName: String, pToken: String) {
        hideMullaLoading()
        KeurApplyAct.start(requireContext(),pName,pToken)
    }

    /**
     * 认证未完成 - 进入认证页面
     */
    override fun showMullaProcessStepsPage() {
        hideMullaLoading()
        onIntent(KeurStepsAct::class.java)
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onKeurEvent(event: KeurEventData) {
        super.onKeurEvent(event)
        when(event.eventType){
            KeurEventData.TYPE.KEUR_SHOW_PRODUCTS -> {//显示可申请产品列表
                _binding?.productLayout?.callOnClick()
            }
            KeurEventData.TYPE.KEUR_PRODUCT_REFRESHED -> {//刷新产品列表
                presenter.loadMullaProductListAction()
            }
            KeurEventData.TYPE.KEUR_PRODUCT_FINISHED -> {
                hideMullaLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 是否是新用户
     */
    private fun isNewUser(): Boolean{
        val dataString = SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_PROCESS)
        if (dataString.isEmpty()){
            return true
        }
        val obj = JSONObject(dataString)
        if (!obj.has("userType")){
            return true
        }
        return obj.optString("userType") == "NEW"
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        presenter?.checkMullaAllPermissionsAgree()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_PRODUCT_LIST_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}